<template>
	<view>
		<view class="tip centerXY-g">
			· 登录后可以继续使用小程序服务<br>
			· 登录会获取您的头像及昵称等信息
		</view>
		<view class="login-box centerXY-g" @click="login">授权登录</view>
		<view class="back-box centerXY-g" @click="back">返回首页</view>
	</view>
</template>

<script>
	import {
		ulogin,
		userinfo
	} from "@/common/http.api.js"
	export default {
		data() {
			return {
				userdata: {}
			}
		},
		methods: {
			back(){
				uni.switchTab({
					url:'/pages/index/index'
				})
			},
			login() {
				let _this = this
				wx.getUserProfile({
					desc: '用于完善用户资料',
					success: async (res) => {
						uni.$loading('正在登录...')
						let { gender, nickName, avatarUrl } = res.userInfo
						_this.userdata = { gender, nickName, avatarUrl } 
						wx.login({
							async success(resu) {
								if (resu.code) {
									// 获取用户code
									_this.userdata.code = resu.code
									// 后端登录
									const result = await ulogin(_this.userdata)
									_this.$store.commit('getUserId',result.data.userId)
									// token 存缓存
									uni.setStorageSync('token',result.data.token)
									// //  userId,userInfo 存vuex
									const userInfo = await userinfo({userId:result.data.userId})
									_this.$store.commit('getUserInfo',userInfo.data)
									if(result.code == 0) uni.$showMsg('登录成功')
									// // 返回上一页
									uni.navigateBack({delta:1})
								} else {
									let err = '登录失败！' + resu.errMsg
									uni.$showMsg(err,'error')
								}
							}
						})
						
					},
				})
			}
		}
	}
</script>

<style lang="scss">
	.tip {
		width: 100%;
		font-weight: bold;
		position: absolute;
		margin: auto;
		transform: translate(-40%, -200%);
	}

	.login-box,
	.back-box {
		position: fixed;
		padding: 0 40rpx;
		background-color: #4d7ff2;
		box-shadow: 0 2rpx 20rpx 0 rgba(0, 0, 0, 0.08);
		width: 80%;
		height: 90rpx;
		border-radius: 20rpx;
		color: #fff;
		font-weight: bold;
		font-size: 16px;
		text-align: center;
		line-height: 90rpx;
	}

	.back-box {
		transform: translate(-50%, 100%);
		background-color: #fff;
		color: gray;
	}
	.login-box:hover{
		background-color:#96c1ff;
	}
	.back-box:hover{
		background-color:#eee;
	}
</style>
